import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { query } from 'express';

import { Repository,Like } from 'typeorm'
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './entities/user.entity'


@Injectable()
export class UserService {

  constructor (
    @InjectRepository(User) private readonly user:Repository<User>

  ){}

  create(createUserDto: CreateUserDto) {
       const data = new User()
       data.name = createUserDto.name;
       data.password = createUserDto.password;
       data.desc = createUserDto.desc;
       return this.user.save(data);
  }

        
 async findAll(query:{keyWord:string,page:number,pageSize:number}) {

    const data = await this.user.find({
      where:{
        name: Like(`%${query.keyWord}%`)
      },
      skip:(query.page -1) * query.pageSize,   //从0开始     相当于limit 0,10
      take:query.pageSize,                     //取10条数据
      order:{
        id:"desc"
      }
    })

   const total = await this.user.count({
      where:{
        name: Like(`%${query.keyWord}%`)
      }
    })

    return {
      data,
      total
    }

  }

  update(id: number, UpdateUserDto: UpdateUserDto) {
    return this.user.update(id,UpdateUserDto)
  }

  remove(id: number) {
    return this.user.delete(id)
  }


  //登录
  async login(body:{name:string,pwd:string,type:string}){

    let data = await this.user.findOne({
      where:{
        name: body.name,
        password: body.pwd
      }
    })
console.log(data);

    if(data){
      return data;
    }else{
      //验证码错误
      return {
        code: 200,
        message: "用户或密码有误",
        error: true
      }
    }

  }



}
